#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    const int INT = 0x3f3f3f3f;
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> f(n, vector<int>(k + 1, -INT)), g(n, vector<int>(k + 1, -INT));
        f[0][0] = -prices[0], g[0][0] = 0;

        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j <= k; j++)
            {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j > 0)
                    g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
            }
        }

        int Max = 0;
        for (int i = 0; i <= k; i++)
        {
            Max = max(Max, g[n - 1][i]);
        }
        return Max;
    }
};


//
class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        vector<vector<int>> dp(2, vector<int>(n));
        dp[0][0] = -prices[0];

        for (int i = 1; i < n; i++)
        {
            dp[0][i] = max(dp[0][i - 1], dp[1][i - 1] - prices[i]);
            dp[1][i] = max(dp[1][i - 1], dp[0][i - 1] + prices[i] - fee);
        }

        return dp[1][n - 1];
    }
};


//
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n);
        dp[0] = nums[0];

        int ret = dp[0];
        for (int i = 1; i < n; i++)
        {
            dp[i] = max(dp[i - 1] + nums[i], nums[i]);
            ret = max(ret, dp[i]);
        }
        return ret;
    }
};


//
class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n + 1), g(n + 1);
        f[0] = g[0] = 0;

        int fmax = INT_MIN, gmin = INT_MAX, sum = 0;
        for (int i = 1; i <= n; i++)
        {
            f[i] = max(f[i - 1] + nums[i - 1], nums[i - 1]);
            fmax = max(f[i], fmax);

            g[i] = min(g[i - 1] + nums[i - 1], nums[i - 1]);
            gmin = min(g[i], gmin);
            sum += nums[i - 1];
        }

        return sum == gmin ? fmax : max(fmax, sum - gmin);
    }
};